package com.harry.decoupling.impl.tool;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections4.SetUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import com.harry.decoupling.defi.tool.DictManager;

@Component
public class DefaultDictManagerImpl implements DictManager {

	@Autowired
	private CacheManager cacheManager;

	private Set<String> dictGroupNameSet = new LinkedHashSet<>();

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, String> dictGroup(String dictGroupName) throws Exception {
		ValueWrapper cacheValue = getDefaultCache().get(cacheKey(dictGroupName));
		if (cacheValue == null) {
			dictGroupNameSet.add(dictGroupName);
			getDefaultCache().put(cacheKey(dictGroupName), new HashMap<String, String>());
			cacheValue = getDefaultCache().get(cacheKey(dictGroupName));
		}
		return (Map<String, String>) cacheValue.get();
	}

	@Override
	public String dict(String dictGroupName, String code) throws Exception {
		return dictGroup(dictGroupName).get(code);
	}

	@Override
	public void add(String dictGroupName, String code, String value) throws Exception {
		Map<String, String> dictGroup = dictGroup(dictGroupName);
		dictGroup.put(code, value);
		getDefaultCache().put(cacheKey(dictGroupName), dictGroup);
	}

	@Override
	public Set<String> dictGroupNames() throws Exception {
		return SetUtils.unmodifiableSet(dictGroupNameSet);
	}

	private Cache getDefaultCache() throws Exception {
		String[] names = cacheManager.getCacheNames().toArray(new String[0]);
		if (names.length > 0) {
			return cacheManager.getCache(names[0]);
		} else {
			return null;
		}
	}

	private Object cacheKey(String dictGroupName) {
		return "DICT_GROUP_NAME_" + dictGroupName;
	}
}
